from jili.core import moheengine as mh
from jili.trade.constants import adapter_subjects as subjects
class AdapterFrame:
    def __init__(self,config={}):
        self.config=config
        self.cmdmap=dict(login="Login",logout="Logout")
        self.adpatermap = {}

    def __getbrokercmd(self,cmds):
        if cmds in self.cmdmap.keys():
            cmds = self.cmdmap[cmds]
        return cmds
    def loadcore(self,tradecore,coretype="ctp"):
        self.tradecore=tradecore
        self.coretype=coretype
        self.up=subjects[self.coretype]["up"]
        self.down=subjects[self.coretype]["down"]
        print("tradecore version",tradecore.getversion())
        print("tradecore up-dowm", self.up,self.down)
    def run(self,config={}):
        if config:
            self.config.update(config)
        mh.subscribe(self.__onmsg, self.up, "")

    # class __dir__(),getattr(a,"call")("i am siiii"),hasattr(a,"call2")
    def __trycall(self,msg):
        print("onmsg:", msg)
        data = msg["2"]
        # print("data-1",data)
        cmd = data["cmd"]
        investorid = msg["1"]
        cmd = self.__getbrokercmd(cmd)
        if investorid in self.adpatermap.keys():  # 是否初始化接口
            adpater = self.adpatermap[investorid]
            if adpater.isLogined:  # 是否login,是执行命令调用
                if hasattr(adpater, cmd):
                    getattr(adpater, cmd)(data)
                else:
                    self.senderror(data["RequestID"], investorid, "no this cmd,please check you code or cmd first")
            else:  # 否，是否login cmd
                if cmd in ["login", "Login"]:  # 是否登陆命令
                    adpater.Login(data)
                elif cmd == "reqAuthenticate":
                    if adpater.reqAuthenticate(adpater.BrokerID, investorid) != 0:
                        self.senderror(data["RequestID"], investorid, "no login, auth err")
                elif cmd in ["reqUserPasswordUpdate", "reqTradingAccountPasswordUpdate"]:
                    getattr(adpater, cmd)(data)
                else:  # 否回复非法
                    self.senderror(data["RequestID"], investorid, "no login,please login first")
        else:  # 没有则初始化
            if cmd in ["login", "Login"]:  # 是否登陆命令
                config = self.config[self.coretype]
                trader = self.tradecore.create(investorid,config)
                brokerid = data["BrokerID"]
                config["BrokerID"]=brokerid
                config["login_data"]=data
                if "private" in data.keys():
                    trader.init(config)
                else:
                    trader.init(config)
                trader.setInvestorID(investorid)
                if trader.Connect() == 0:
                    self.senderror[investorid] = trader
                    if trader.reqAuthenticate(brokerid, investorid) == 0:
                        trader.Login(data)
                    else:
                        self.senderror(data["RequestID"], investorid, "no login, auth err")
                else:
                    self.senderror(data["RequestID"], investorid, "connect failed; check ip or port is telnet?")
            else:  # 否回复非法
                self.senderror(data["RequestID"], investorid, "no login,please login first")
    def __onmsg(self,msg):
        try:
            self.__trycall(msg)
        except Exception as e:
            try:
                data = msg["2"]
                self.senderror(data["RequestID"], data["InvestorID"], e.args[0])
                print("onmsg sysyerror:", e)
            except Exception as e:
                print(e)
    def senderror(self,reuestid, investorid, info, cmd="OnSysError"):
        rspinfo = dict(ErrorID=1, ErrorMsg="error")
        if isinstance(info, dict):
            rspinfo.update(info)
        else:
            rspinfo["ErrorMsg"] = info
        msg = {}
        msg["RspInfo"] = rspinfo
        msg["RequestID"] = reuestid
        msg["cmd"] = cmd
        msg["IsLast"] = True
        msg["data"] = {}
        mh.safesend(self.down, investorid, msg)